<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\SubSettlement;
use App\Models\Settlement;
use App\Models\Freelancer;
use Faker\Factory as Faker;

class SubSettlementSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create('zh_CN');

        // 获取可用的结算单列表
        $settlements = Settlement::all();
        
        if ($settlements->isEmpty()) {
            $this->command->info('没有找到结算单，跳过创建子结算单...');
            return;
        }

        // 获取可用的自由职业者列表
        $freelancers = Freelancer::all();
        
        if ($freelancers->isEmpty()) {
            $this->command->info('没有找到自由职业者，跳过创建子结算单...');
            return;
        }

        $statuses = [
            SubSettlement::STATUS_VERIFYING,
            SubSettlement::STATUS_PENDING_TAX,
            SubSettlement::STATUS_PENDING_SUBMIT,
            SubSettlement::STATUS_PENDING_DISTRIBUTE,
            SubSettlement::STATUS_DISTRIBUTING,
            SubSettlement::STATUS_COMPLETED,
            SubSettlement::STATUS_CANCELLED,
            SubSettlement::STATUS_DISTRIBUTE_FAILED,
            SubSettlement::STATUS_VERIFY_FAILED,
            SubSettlement::STATUS_REFUNDED
        ];

        // 为每个结算单创建子结算单
        foreach ($settlements as $settlement) {
            // 每个结算单随机创建3-8个子结算单
            $subSettlementCount = $faker->numberBetween(3, 8);
            $usedFreelancers = [];

            for ($i = 0; $i < $subSettlementCount; $i++) {
                // 选择一个未使用过的自由职业者
                $availableFreelancers = $freelancers->whereNotIn('id', $usedFreelancers);
                
                if ($availableFreelancers->isEmpty()) {
                    break; // 没有更多可用的自由职业者
                }

                $freelancer = $faker->randomElement($availableFreelancers->toArray());
                $usedFreelancers[] = $freelancer['id'];

                $status = $faker->randomElement($statuses);
                
                // 生成金额数据
                $preSettlementAmount = $faker->randomFloat(2, 500, 5000);
                $serviceFeeRate = $faker->randomElement([0.05, 0.08, 0.10, 0.15]); // 5%, 8%, 10%, 15%
                $serviceFee = $preSettlementAmount * $serviceFeeRate;
                $commission = $preSettlementAmount - 0; // 初始佣金按未扣税
                $tax = round($preSettlementAmount * $faker->randomFloat(2, 0.03, 0.12), 2);
                
                $createdAt = $faker->dateTimeBetween($settlement['created_at'], 'now');
                
                $subSettlement = SubSettlement::create([
                    'tenant_id' => $settlement['tenant_id'],
                    'settlement_id' => $settlement['id'],
                    'freelancer_id' => $freelancer['id'],
                    'freelancer_name' => $freelancer['name'],
                    'freelancer_phone' => $freelancer['phone'],
                    'freelancer_id_card' => $freelancer['id_card'],
                    'freelancer_bank_account' => $freelancer['bank_account'],
                    'freelancer_bank_name' => $freelancer['bank_name'],
                    'pre_settlement_amount' => $preSettlementAmount,
                    'commission' => max(0, $commission - $tax),
                    'service_fee' => $serviceFee,
                    'service_fee_rate' => $serviceFeeRate,
                    'tax' => $tax,
                    'required_balance' => $preSettlementAmount + $serviceFee,
                    'status' => $status,
                    'payment_remarks' => $faker->optional(0.6)->sentence,
                    'electronic_receipt' => $faker->optional(0.4)->passthrough([
                        'receipt_number' => $faker->numerify('REC########'),
                        'bank_name' => $faker->randomElement(['中国银行', '工商银行', '建设银行', '农业银行']),
                        'transaction_time' => $faker->dateTime->format('Y-m-d H:i:s'),
                        'amount' => $commission,
                        'status' => 'success'
                    ]),
                    'created_by' => 1,
                    'created_at' => $createdAt,
                ]);

                // 根据状态设置相应的时间戳
                $updates = [];
                switch ($status) {
                    case SubSettlement::STATUS_PENDING_TAX:
                        $updates['verified_at'] = $faker->dateTimeBetween($createdAt, 'now');
                        $updates['verified_by'] = 1;
                        $updates['status_description'] = $faker->randomElement(['等待算税结果', '准备发起算税', '等待税务计算']);
                        break;

                    case SubSettlement::STATUS_PENDING_SUBMIT:
                        $updates['verified_at'] = $faker->dateTimeBetween($createdAt, 'now');
                        $updates['verified_by'] = 1;
                        break;
                        
                    case SubSettlement::STATUS_PENDING_DISTRIBUTE:
                        $verifiedAt = $faker->dateTimeBetween($createdAt, 'now');
                        $updates['verified_at'] = $verifiedAt;
                        $updates['verified_by'] = 1;
                        $updates['submitted_at'] = $faker->dateTimeBetween($verifiedAt, 'now');
                        $updates['submitted_by'] = 1;
                        break;
                        
                    case SubSettlement::STATUS_DISTRIBUTING:
                        $verifiedAt = $faker->dateTimeBetween($createdAt, 'now');
                        $submittedAt = $faker->dateTimeBetween($verifiedAt, 'now');
                        $updates['verified_at'] = $verifiedAt;
                        $updates['verified_by'] = 1;
                        $updates['submitted_at'] = $submittedAt;
                        $updates['submitted_by'] = 1;
                        $updates['distribute_started_at'] = $faker->dateTimeBetween($submittedAt, 'now');
                        $updates['distributed_by'] = 1;
                        break;
                        
                    case SubSettlement::STATUS_COMPLETED:
                        $verifiedAt = $faker->dateTimeBetween($createdAt, 'now');
                        $submittedAt = $faker->dateTimeBetween($verifiedAt, 'now');
                        $distributeStartedAt = $faker->dateTimeBetween($submittedAt, 'now');
                        $updates['verified_at'] = $verifiedAt;
                        $updates['verified_by'] = 1;
                        $updates['submitted_at'] = $submittedAt;
                        $updates['submitted_by'] = 1;
                        $updates['distribute_started_at'] = $distributeStartedAt;
                        $updates['distributed_at'] = $faker->dateTimeBetween($distributeStartedAt, 'now');
                        $updates['distributed_by'] = 1;
                        break;
                        
                    case SubSettlement::STATUS_CANCELLED:
                        if ($faker->boolean(70)) {
                            $updates['verified_at'] = $faker->dateTimeBetween($createdAt, 'now');
                            $updates['verified_by'] = 1;
                        }
                        $updates['cancelled_at'] = $faker->dateTimeBetween($createdAt, 'now');
                        $updates['cancelled_by'] = 1;
                        $updates['status_description'] = $faker->randomElement(['用户取消', '系统取消', '管理员取消']);
                        break;
                        
                    case SubSettlement::STATUS_DISTRIBUTE_FAILED:
                    case SubSettlement::STATUS_REFUNDED:
                        $verifiedAt = $faker->dateTimeBetween($createdAt, 'now');
                        $submittedAt = $faker->dateTimeBetween($verifiedAt, 'now');
                        $distributeStartedAt = $faker->dateTimeBetween($submittedAt, 'now');
                        $updates['verified_at'] = $verifiedAt;
                        $updates['verified_by'] = 1;
                        $updates['submitted_at'] = $submittedAt;
                        $updates['submitted_by'] = 1;
                        $updates['distribute_started_at'] = $distributeStartedAt;
                        $updates['distributed_by'] = 1;
                        if ($status === SubSettlement::STATUS_DISTRIBUTE_FAILED) {
                            $updates['status_description'] = $faker->randomElement(['银行卡信息错误', '账户被冻结', '网络异常']);
                        } else {
                            $updates['distributed_at'] = $faker->dateTimeBetween($distributeStartedAt, 'now');
                            $updates['status_description'] = '用户申请退票';
                        }
                        break;
                        
                    case SubSettlement::STATUS_VERIFY_FAILED:
                        $updates['verified_at'] = $faker->dateTimeBetween($createdAt, 'now');
                        $updates['verified_by'] = 1;
                        $updates['status_description'] = $faker->randomElement(['资料不全', '金额有误', '信息核实失败']);
                        break;
                }
                
                if (!empty($updates)) {
                    $subSettlement->update($updates);
                }
            }
        }

        $this->command->info('SubSettlementSeeder completed successfully!');
        $totalCount = SubSettlement::count();
        $this->command->info("Created {$totalCount} sub-settlement records with various statuses.");
    }
}
